package com.zhongwang.mms.module.half.service;


import com.zhongwang.mms.common.ImportCallBack;
import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.HInventory;
import com.zhongwang.mms.gen.entity.User;
import com.zhongwang.mms.module.half.dao.HInventoryDao;
import com.zhongwang.mms.module.half.dao.HalfInveAdjDao;
import com.zhongwang.mms.module.half.dao.InventoryCheckDao;
import com.zhongwang.mms.module.half.model.*;
import com.zhongwang.mms.module.purchase.dao.PurCheckDao;
import com.zhongwang.mms.module.purchase.model.check.PCheckDetailExcelModel;
import com.zhongwang.mms.module.purchase.model.check.PCheckDetailQueryModel;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.FileUtils;
import com.zhongwang.mms.util.ShiroUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


/**
 * 盘点
 */
@Log4j2
@Service
public class InventoryCheckService {

    @Autowired
    private InventoryCheckDao inventoryCheckDao;
    @Autowired
    private HBasicService hBasicService;
    @Autowired
    private LogService logService;
    @Autowired
    private HInventoryDao hInventoryDao;
    @Autowired
    private HalfInveAdjDao hAdjustDao;
    @Autowired
    private PurCheckDao purCheckDao;

    @Value("${user.upload.path}")
    private String uploadPath;
    private String msg = "";

    /**
     * 盘点计划列表
     * @param hCheckPlanModel
     * @return
     */
    public List<HCheckPlanModel> findCheckPlan(HCheckPlanModel hCheckPlanModel){

        return inventoryCheckDao.findCheckPlan(hCheckPlanModel);
    }

    /**
     * 删除盘点计划记录
     *
     * @param hCheckPlanModel 变更计划信息
     * @return 影响行数
     */
    public int deleteCheckPlan(HCheckPlanModel hCheckPlanModel) {
         inventoryCheckDao.deleteCheckPlanRecordById(hCheckPlanModel);
        return 1;
    }

    /**
     * 根据主键获取盘点计划
     * @param cpnId
     * @return
     */
    public HCheckPlanModel getCheckPlanByPrimary(Integer cpnId) {
        return inventoryCheckDao.getHCheckPlanByByPrimaryKey(cpnId);
    }

    /**
     * 保存计划
     * @param hCheckPlanModel
     * @return
     */
    @Transactional
    public boolean planSave(HCheckPlanModel hCheckPlanModel) {
        try {
            //如果为空则插入盘点计划数据
            if (null == hCheckPlanModel.getCpnId()) {
                hCheckPlanModel.setCpnCode(hBasicService.generateIPCOrderCode());
                hCheckPlanModel.setCpnStatus(1);
                hCheckPlanModel.setCpnPlanStatus(1);
                hCheckPlanModel.setCpnResStatus(1);
                hCheckPlanModel.setCpnAdjStatus(1);
                hCheckPlanModel.setCpnPalStatus(1);
                hCheckPlanModel.setCpnDate(new Date());
                hCheckPlanModel.setCpnMaker(ShiroUtils.getUser().getName());
                inventoryCheckDao.insertCheckPlanSelective(hCheckPlanModel);
                logService.saveLog("新增盘点计划", "盘点计划编号：" + hCheckPlanModel.getCpnCode());
            }
            //如果不为空则更新盘点计划数据
            else {
                HCheckPlanModel beforePCheckPlanModel = inventoryCheckDao.getHCheckPlanByByPrimaryKey(hCheckPlanModel.getCpnId());
                inventoryCheckDao.updateCheckPlanByPrimaryKeySelective(hCheckPlanModel);
                HCheckPlanModel afterPCheckPlanModel = inventoryCheckDao.getHCheckPlanByByPrimaryKey(hCheckPlanModel.getCpnId());
                logService.saveLog("更新盘点计划", beforePCheckPlanModel, afterPCheckPlanModel);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 提交盘点计划
     * @param hCheckPlanModel
     * @return
     */
    @Transactional
    public boolean planSubmit(HCheckPlanModel hCheckPlanModel) {
        try {
//            param.setCpnStatus(2);
            hCheckPlanModel.setCpnPlanStatus(3);
            hCheckPlanModel.setCpnResStatus(2);
            inventoryCheckDao.updateCheckPlanByPrimaryKeySelective(hCheckPlanModel);
            HCheckPlanModel removePCheckPlanModel = inventoryCheckDao.getHCheckPlanByByPrimaryKey(hCheckPlanModel.getCpnId());
            logService.saveLog("提交盘点计划", "提交的盘点计划编号是：" + removePCheckPlanModel.getCpnCode());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 根据盘点计划编码获取盘点明细列表
     * @param hCheckDetailModel
     * @return
     */
    public List<HCheckDetailModel> findDetailList(HCheckDetailModel hCheckDetailModel) {
        return inventoryCheckDao.findDetailList(hCheckDetailModel);
    }

    public List<HInventory> getInventoryList(HInventoryQueryModel query) {

        query.setItyMatTypeQuery(5);//外协件和外购件（单独使用）
        return hInventoryDao.selectHInventoryByQuery(query);
    }

    /**
     * 根据传过来的库存主键创建盘点明细
     * @param hCheckDetailModel
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult detailCreate(HCheckDetailModel hCheckDetailModel) {
        JsonResult jsonResult = new JsonResult();
        try {
            //获取库存列表
            List<HInventory> hInventoryList = hInventoryDao.findInventoryListByityIds(hCheckDetailModel.getItyIds());
            HCheckPlanModel hCheckPlanModel = inventoryCheckDao.getHCheckPlanByByCpnCode(hCheckDetailModel.getCpnCode());
            Set<HInventory> existPInventorySet = new HashSet<>();
            List<HCheckDetailModel> pCheckDetailModelList = inventoryCheckDao.findDetailListByCdlCpnId(hCheckPlanModel.getCpnId());
            List<String> warningMessageList = new ArrayList<String>();
            for (HInventory pInventory : hInventoryList) {
                for (HCheckDetailModel testModel : pCheckDetailModelList) {
                    if (testModel.getCdlItyId().equals(pInventory.getItyId())) {
                        warningMessageList.add("选中的物料描述为【" + pInventory.getItyMatName() + "】的库存信息已经添加进明细表中。");
                        existPInventorySet.add(pInventory);
                    }
                }
            }
            for (HInventory existPInventory:existPInventorySet) {
                hInventoryList.remove(existPInventory);
            }
            //验证当前盘点计划状态是否是已执行
            if (hCheckPlanModel.getCpnPlanStatus().equals(1)) {
                //创建只有主键和盘点计划状态的模型，只为更新状态使用。
                HCheckPlanModel updateCpnPlanStatusModel = new HCheckPlanModel();
                updateCpnPlanStatusModel.setCpnId(hCheckPlanModel.getCpnId());
                updateCpnPlanStatusModel.setCpnPlanStatus(2);
                updateCpnPlanStatusModel.setCpnStatus(2);
                inventoryCheckDao.updateCheckPlanByPrimaryKeySelective(updateCpnPlanStatusModel);
            }
            for (HInventory hInventory : hInventoryList) {
                HCheckDetailModel hCheckDetailModel1 = new HCheckDetailModel();
                hCheckDetailModel1.setCdlMatName(hInventory.getItyMatName());
                hCheckDetailModel1.setCdlMatCode(hInventory.getItySapCode());
                hCheckDetailModel1.setCdlUnit(hInventory.getItyUnit());
                hCheckDetailModel1.setCdlPrice(hInventory.getItyPrice());
                hCheckDetailModel1.setCdlTrackCode(hInventory.getItyTrackCode());
                hCheckDetailModel1.setCdlProName(hInventory.getItyProName());
                hCheckDetailModel1.setCdlProCode(hInventory.getItyProCode());
                hCheckDetailModel1.setCdlWhiId(hInventory.getItyWhiId());
                hCheckDetailModel1.setCdlPosition(hInventory.getItyPosition());
                //pCheckDetailModel.setCdlBookkeepingDate(hInventory.getItyBookkeepingDate());
                hCheckDetailModel1.setCdlStockType(hInventory.getItyStockType());
                hCheckDetailModel1.setCdlCpnId(hCheckPlanModel.getCpnId());
                hCheckDetailModel1.setCdlItyId(hInventory.getItyId());
                hCheckDetailModel1.setCdlStatus(1);
                hCheckDetailModel1.setCdlItyNum(hInventory.getItyNum());
                inventoryCheckDao.insertCheckDetailSelective(hCheckDetailModel1);
            }
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            if (warningMessageList.size() > 0) {
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setMsg(warningMessageList.toString().replace(",","<br>"));
            } else {
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
                jsonResult.setMsg("添加明细成功！");
            }
            logService.saveLog("添加盘点明细", "被添加盘点明细的盘点计划编号是：" + hCheckDetailModel.getCpnCode());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("添加明细失败！");
        }
        return jsonResult;
    }

    /**
     * 提交盘点结果
     * @param cdlCpnId
     * @return
     */
    @Transactional
    public JsonResult resultSubmit(Integer cdlCpnId) {
        JsonResult jsonResult = new JsonResult();
        try {
            List<HCheckDetailModel> hCheckDetailModelList = inventoryCheckDao.findDetailListByCdlCpnId(cdlCpnId);
            for (HCheckDetailModel hCheckDetailModel : hCheckDetailModelList) {
                if(hCheckDetailModel.getCdlNum()==null){
                    jsonResult.setType(JsonResult.ResultType.ERROR);
                    jsonResult.setMsg("请填写所有盘点结果才可以进行提交！");
                    return jsonResult;
                }
            }
            HCheckPlanModel resultSubmitModel = new HCheckPlanModel();
            resultSubmitModel.setCpnId(cdlCpnId);
            resultSubmitModel.setCpnResStatus(3);
            resultSubmitModel.setCpnAdjStatus(2);
            inventoryCheckDao.updateCheckPlanByPrimaryKeySelective(resultSubmitModel);
            HCheckPlanModel checkPlanModel = inventoryCheckDao.getHCheckPlanByByPrimaryKey(cdlCpnId);
            logService.saveLog("【成品库】提交盘点结果", "提交盘点结果的计划编号是：" + checkPlanModel.getCpnCode());
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("提交盘点结果成功！");
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error(ex.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("提交盘点结果失败！");
        }
        return jsonResult;
    }

    /**
     * 盘点结果列表
     * @param hCheckDetailModel
     * @return
     */
    public List<HCheckDetailModel> findResultList(HCheckDetailModel hCheckDetailModel) {
        return inventoryCheckDao.findResultList(hCheckDetailModel);
    }

    /**
     * 单条盘点确定保存
     * @param hCheckDetailModel
     * @return
     */
    public boolean resultCheck(HCheckDetailModel hCheckDetailModel) {
        try {
            HCheckDetailModel hCheckDetailModel1 = inventoryCheckDao.getHCheckDetailByPrimaryKey(hCheckDetailModel.getCdlId());
            HCheckDetailModel checkDetailModel = new HCheckDetailModel();
            checkDetailModel.setCdlId(hCheckDetailModel.getCdlId());
            if (hCheckDetailModel.getCdlNum() > hCheckDetailModel1.getCdlItyNum()) {
                checkDetailModel.setCdlCheckStatus(1);
            } else if (hCheckDetailModel.getCdlNum() < hCheckDetailModel1.getCdlItyNum()) {
                checkDetailModel.setCdlCheckStatus(2);
            }
            checkDetailModel.setCdlNum(hCheckDetailModel.getCdlNum());
            checkDetailModel.setCdlPalVal(checkDetailModel.getCdlNum() - hCheckDetailModel1.getCdlItyNum());
            checkDetailModel.setCdlStatus(2);
            inventoryCheckDao.updateHCheckDetailByPrimaryKeySelective(checkDetailModel);
            logService.saveLog("【成品库】盘点明细", "被盘点的明细的物料描述是：" + hCheckDetailModel1.getCdlMatName());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 调整损益差和备注
     * @param hCheckDetailModel
     * @return
     */
    @Transactional
    public JsonResult adjustEdit(HCheckDetailModel hCheckDetailModel) {
        JsonResult jsonResult = new JsonResult();
        try {
            if (hCheckDetailModel.getCdlPalVal() == 0) {
                hCheckDetailModel.setCdlCheckStatus(null);
            } else if (hCheckDetailModel.getCdlPalVal() > 0) {
                hCheckDetailModel.setCdlCheckStatus(2);
            } else {
                hCheckDetailModel.setCdlCheckStatus(1);
            }
            inventoryCheckDao.updateHCheckDetailByPrimaryKeySelective(hCheckDetailModel);
            logService.saveLog("【成品库】盘点损益调整", "");
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("调整成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("调整失败！");
        }
        return jsonResult;
    }

    /**
     * 提交盘点损益调整
     * @param cdlCpnId
     * @return
     */
    @Transactional
    public JsonResult adjustSubmit(Integer cdlCpnId) {
        JsonResult jsonResult = new JsonResult();
        try {
            List<HCheckDetailModel> hCheckDetailModels = inventoryCheckDao.findDetailListByCdlCpnId(cdlCpnId);

            for (HCheckDetailModel hCheckDetailModel : hCheckDetailModels) {
                //生成库存调整申请 不含申请者信息与申请时间
                HAdjustmentApplyModel hAdjustmentApplyModel = new HAdjustmentApplyModel();
                hAdjustmentApplyModel.setAjaDeOvNum(hCheckDetailModel.getCdlNum());
                hAdjustmentApplyModel.setAjaItyNum(hCheckDetailModel.getCdlItyNum());
                hAdjustmentApplyModel.setAjaItyStatus(1);
                hAdjustmentApplyModel.setAjaCpnId(hCheckDetailModel.getCdlCpnId());
                hAdjustmentApplyModel.setAjaItyId(hCheckDetailModel.getCdlItyId());
                hAdjustmentApplyModel.setAjaCdlId(hCheckDetailModel.getCdlId());
                inventoryCheckDao.insertAdjustmentApplySelective(hAdjustmentApplyModel);
            }
            //更改计划状态
            HCheckPlanModel resultSubmitModel = new HCheckPlanModel();
            resultSubmitModel.setCpnId(cdlCpnId);
            resultSubmitModel.setCpnAdjStatus(3);
            resultSubmitModel.setCpnPalStatus(2);
            inventoryCheckDao.updateCheckPlanByPrimaryKeySelective(resultSubmitModel);
            HCheckPlanModel checkPlanModel = inventoryCheckDao.getHCheckPlanByByPrimaryKey(cdlCpnId);
            logService.saveLog("【成品库】提交盘点损益调整", "提交盘点损益调整的计划编号是：" + checkPlanModel.getCpnCode());
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("提交盘点调整成功！");
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error(ex.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("提交盘点调整失败！");
        }
        return jsonResult;
    }

    /**
     * 撤销盘点损益调整
     * @param cdlCpnId
     * @return
     */
    @Transactional
    public JsonResult adjustRevoke(Integer cdlCpnId) {
        JsonResult jsonResult = new JsonResult();
        try {
            //检测损益表是否提交
            HCheckPlanModel checkPlanModel = inventoryCheckDao.getHCheckPlanByByPrimaryKey(cdlCpnId);
            if (checkPlanModel.getCpnPalStatus().equals(3)) {
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setMsg("损益表已提交，请撤销后，再撤销盘点损益调整。");
                return jsonResult;
            }
            //删除损益表相关数据
            inventoryCheckDao.deleteHAdjustmentApplyByAjaCpnId(cdlCpnId);
            //更改计划状态
            HCheckPlanModel resultSubmitModel = new HCheckPlanModel();
            resultSubmitModel.setCpnId(cdlCpnId);
            resultSubmitModel.setCpnAdjStatus(2);
            resultSubmitModel.setCpnPalStatus(1);
            inventoryCheckDao.updateCheckPlanByPrimaryKeySelective(resultSubmitModel);

            logService.saveLog("【成品库】撤销盘点损益调整", "撤销盘点损益调整的计划编号是：" + checkPlanModel.getCpnCode());
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error(ex.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("损益表已提交，请撤销后，再撤销盘点损益调整。");
            return jsonResult;
        }
        jsonResult.setType(JsonResult.ResultType.SUCCESS);
        jsonResult.setMsg("撤销盘点损益调整成功。");
        return jsonResult;
    }

    /**
     * 获得盘点损益表列表数据
     * @param param
     * @return
     */
    public List<HAdjustmentApplyModel> palList(HAdjustmentApplyModel param) {
        return inventoryCheckDao.selectHAdjustmentApplyModelSelectiveByCdlCpnId(param);
    }

    /**
     * 获取汇总表信息
     * @param param
     * @return
     */
    public List<HAdjustmentApplyModel> palSumList(HAdjustmentApplyModel param) {
        return inventoryCheckDao.palSumList(param);
    }

    /**
     * 提交损益表
     * @param param
     * @return
     */
    @Transactional
    public JsonResult palSubmit(HAdjustmentApplyModel param) {
        JsonResult jsonResult = new JsonResult();
        try {
            //获取损益表信息
            List<HAdjustmentApplyModel> adjustmentApplyModelList = inventoryCheckDao.selectHAdjustmentApplyModelSelectiveByPrimaryKeys(param.getAjaIds());
            //遍历生成调整申请单
            for (HAdjustmentApplyModel hAdjustmentApplyModel : adjustmentApplyModelList) {
                HAdjustModel hAdjustModel = new HAdjustModel();
                hAdjustModel.setAdjAjaId(hAdjustmentApplyModel.getAjaId());
                hAdjustModel.setAdjType(2);
                hAdjustModel.setAdjStatus(2);
                hAdjustModel.setAdjNum(hAdjustmentApplyModel.getAjaNum());
                HInventory hInventory = hInventoryDao.selectAllById(hAdjustmentApplyModel.getAjaItyId());
                //如果不为空则是由库存选择来的盘点
                if (null != hInventory) {
                    hAdjustModel.setAdjNewFlag(0);
                }
                //如果为空则是新增的盘点
                else {
                    hAdjustModel.setAdjNewFlag(1);
                }
                HAdjustmentApplyModel updateItyStatusModel = new HAdjustmentApplyModel();
                updateItyStatusModel.setAjaId(hAdjustmentApplyModel.getAjaId());
                updateItyStatusModel.setAjaItyStatus(2);
                updateItyStatusModel.setAjaAdjId(hAdjustModel.getAdjId());
                inventoryCheckDao.updateHAdjustmentApplyModelAjaItyStatus(updateItyStatusModel);
                logService.saveLog("【成品库】创建调整申请", "根据盘点损益结果创建调整申请。");
            }
            HCheckPlanModel hCheckPlanModel = new HCheckPlanModel();
            hCheckPlanModel.setCpnId(param.getCdlCpnId());
            hCheckPlanModel.setCpnPalStatus(3);
            hCheckPlanModel.setCpnStatus(3);
            inventoryCheckDao.updateCheckPlanByPrimaryKeySelective(hCheckPlanModel);
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("提交成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("提交失败");
        }
        return jsonResult;
    }

    /**
     * 删除盘点计划
     * @param param
     * @return
     */
    @Transactional
    public boolean planRemove(HCheckPlanModel param) {
        try {
            param.setCpnStatus(0);
            inventoryCheckDao.updateCheckPlanByPrimaryKeySelective(param);
            HCheckPlanModel removePCheckPlanModel = inventoryCheckDao.getHCheckPlanByByPrimaryKey(param.getCpnId());
            logService.saveLog("删除盘点计划", "删除的盘点计划编号是：" + removePCheckPlanModel.getCpnCode());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 撤销盘点计划
     * @param param
     * @return
     */
    @Transactional
    public JsonResult planRevoke(HCheckPlanModel param) {
        JsonResult jsonResult = new JsonResult();
        try {
            Integer checkCount = inventoryCheckDao.getCheckDetailCheckCountByCdlCpnId(param.getCpnId());
            if (checkCount > 0) {
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setMsg("有盘点结果已经进行盘点，不可撤销！");
            } else {
                param.setCpnPlanStatus(2);
                param.setCpnResStatus(1);
                inventoryCheckDao.updateCheckPlanByPrimaryKeySelective(param);
                HCheckPlanModel removePCheckPlanModel = inventoryCheckDao.getHCheckPlanByByPrimaryKey(param.getCpnId());
                logService.saveLog("撤销盘点计划", "撤销的盘点计划编号是：" + removePCheckPlanModel.getCpnCode());
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
                jsonResult.setMsg("撤销成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("撤销失败！");
        }
        return jsonResult;
    }

    /**
     * 新增盘点
     * @param param
     * @return
     */
    public boolean checkAdd(HCheckDetailModel param) {
        try {
            param.setCdlCpnId(inventoryCheckDao.getHCheckPlanByByCpnCode(param.getCpnCode()).getCpnId());
            param.setCdlStatus(2);
            param.setCdlIsNewFlag(1);
            param.setCdlItyNum(0d);
            if (param.getCdlNum() > param.getCdlItyNum()) {
                param.setCdlCheckStatus(1);
            } else if (param.getCdlNum() < param.getCdlItyNum()) {
                param.setCdlCheckStatus(2);
            }
            param.setCdlPalVal(param.getCdlNum() - param.getCdlItyNum());
            inventoryCheckDao.insertCheckDetailSelective(param);
            logService.saveLog("【成品库】新增盘点明细", "新增盘点明细入料描述：" + param.getCdlMatName());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 撤销盘点结果
     * @param cdlCpnId
     * @return
     */
    @Transactional
    public boolean resultRevoke(Integer cdlCpnId) {
        try {
            HCheckPlanModel checkPlanModel = inventoryCheckDao.getHCheckPlanByByPrimaryKey(cdlCpnId);
            HCheckPlanModel resultRevokeModel = new HCheckPlanModel();
            if (checkPlanModel.getCpnAdjStatus() == 3) {
                return false;
            }
            resultRevokeModel.setCpnId(cdlCpnId);
            resultRevokeModel.setCpnResStatus(2);
            resultRevokeModel.setCpnAdjStatus(1);
            inventoryCheckDao.updateCheckPlanByPrimaryKeySelective(resultRevokeModel);
            logService.saveLog("【成品库】撤销盘点结果", "撤销盘点结果的计划编号是：" + checkPlanModel.getCpnCode());
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error(ex.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 批量删除
     * @param param
     * @return
     */
    @Transactional
    public JsonResult detailRemoves(HCheckDetailModel param) {
        JsonResult jsonResult = new JsonResult();
        try {
            if (!param.getCdlIds().equals("")) {
                Integer cdlId = Integer.valueOf(param.getCdlIds().split(",")[0]);
                HCheckDetailModel hCheckDetailModel = inventoryCheckDao.getHCheckDetailByPrimaryKey(cdlId);
                inventoryCheckDao.deleteCheckDetailByPrimaryKeys(param.getCdlIds());
                if (inventoryCheckDao.getCheckDetailCountByCdlCpnId(hCheckDetailModel.getCdlCpnId()) == 0) {
                    HCheckPlanModel hCheckPlanModel = inventoryCheckDao.getHCheckPlanByByPrimaryKey(hCheckDetailModel.getCdlCpnId());
                    hCheckPlanModel.setCpnPlanStatus(1);
                    hCheckPlanModel.setCpnStatus(1);
                    inventoryCheckDao.updateCheckPlanByPrimaryKeySelective(hCheckPlanModel);
                }
                logService.saveLog("【成品库】批量删除盘点明细", "批量删除盘点明细");
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
                jsonResult.setMsg("删除盘点明细成功。");
            } else {
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setMsg("请选择要被删除的盘点明细。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("删除盘点明细失败。");
        }
        return jsonResult;
    }

    /**
     * 导出盘点计划
     * @param response
     * @param cpnId
     */
    public void planExport(HttpServletResponse response, Integer cpnId) {
        List<PCheckDetailExcelModel> list = inventoryCheckDao.findHCheckPlanByPrimaryKey(cpnId);
        //PCheckPlanModel pCheckPlanModel = purCheckDao.getPCheckPlanByByPrimaryKey(cpnId);
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String path = uploadPath + user.getAccount() + "/";
        FileUtils.export(path, "盘点计划.xls", PCheckDetailExcelModel.class, "sheet1", list, response);
        //logService.saveLog("【成品库】导出盘点计划", "计划编号是：" + pCheckPlanModel.getCpnCode());
    }

    /**
     * 清空盘点结果
     * @param param
     * @return
     */
    @Transactional
    public boolean resultClean(PCheckDetailQueryModel param) {
        try {
             List<HCheckDetailModel> pCheckDetailModelList = inventoryCheckDao.findDetailListByCdlCpnId(param.getCdlCpnId());
            for (HCheckDetailModel pCheckDetailModel : pCheckDetailModelList) {
                if (pCheckDetailModel.getCdlIsNewFlag() == 1) {
                    inventoryCheckDao.deleteCheckDetailByPrimaryKey(pCheckDetailModel.getCdlId());
                }
            }
            inventoryCheckDao.resultClean(param.getCdlCpnId());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 盘点结果导入
     * @param file
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String resultImport(MultipartFile file) {
        try {
            FileUtils.importExcel(file, PCheckDetailExcelModel.class, new HCheckDetailListener(purCheckDao,inventoryCheckDao, new ImportCallBack() {
                @Override
                public void onSuccess() {
                    msg = "导入完成";
                }

                @Override
                public void onWarning(List list) {
                    msg = "部份数据无法导入，请点击下载检查数据内容";
                    exportErrorExcel(list);
                }
            }));
            logService.saveLog("【成品库】导入盘点结果", "导入盘点结果成功！");

        } catch (IOException e) {
            return "导入失败";
        }
        return msg;
    }

    /**
     * 异常数据导出到Excel
     *
     * @param errorList
     */
    private void exportErrorExcel(List<PCheckDetailExcelModel> errorList) {
        if (errorList.size() <= 0) {
            return;
        }
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String path = uploadPath + user.getAccount() + "/";
        FileUtils.genExcel(path, "checkError.xls", PCheckDetailExcelModel.class, "sheet1", errorList);
    }

    /**
     * 删除盘点明细
     * @param param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean detailRemove(HCheckDetailModel param) {
        try {
            HCheckDetailModel pCheckDetailModel = inventoryCheckDao.getHCheckDetailByPrimaryKey(param.getCdlId());
            inventoryCheckDao.deleteCheckDetailByPrimaryKey(param.getCdlId());
            if (inventoryCheckDao.getCheckDetailCountByCdlCpnId(pCheckDetailModel.getCdlCpnId()) == 0) {
                HCheckPlanModel pCheckPlanModel = inventoryCheckDao.getHCheckPlanByByPrimaryKey(pCheckDetailModel.getCdlCpnId());
                pCheckPlanModel.setCpnPlanStatus(1);
                pCheckPlanModel.setCpnStatus(1);
                inventoryCheckDao.updateCheckPlanByPrimaryKeySelective(pCheckPlanModel);
            }
            logService.saveLog("【成品库】删除盘点明细", "被删除的盘点明细的物料描述是：" + pCheckDetailModel.getCdlMatName());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return false;
        }
        return true;
    }
}


